package com.example.nio.service.impl;

import cn.hutool.core.date.DateTime;
import com.example.nio.commons.*;
import com.example.nio.config.FlowNumHandler;
import com.example.nio.config.MessageSendService;
import com.example.nio.dao.AgentMapper;
import com.example.nio.dao.StatisReportMapper;
import com.example.nio.dao.WxUserMapper;
import com.example.nio.service.MessageDisposeService;
import com.example.nio.service.StatisReportService;
import com.example.nio.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class MessageDisposeServiceImpl implements MessageDisposeService {
    @Autowired
    private FlowNumHandler flowNumHandler;
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private MessageSendService messageSendService;
    @Autowired
    private StatisReportMapper statisReportMapper;

    // 发送等待队列给在线的客服
    private void sendListWaitToAgent(){
        // 把等待队列 发送给在线客服
        ChatMessage systemMessage = new ChatMessage();
        List<Agent> agentList = AssignedUtil.getAgentByDepartment("1");
        // 客服上线 告诉其他已在线的客服
        if (agentList.size() > 0){
            systemMessage.setMsgType("waitList");
            List<User> userList = ListWaitUtil.getUserList("1");
            userList.stream().forEach(item ->  {
                systemMessage.setUserList2(item.getNickname(),null,item.getOpenId(),"",item.getMessageSource());
            });
            for (Agent agent1: agentList){
                BridgeUtil.toClient(systemMessage,agent1);
            }
        }
    }
    
    @Override
    public void messageHandling(ChatMessage chatMessage) {
        String department = "1";
        Agent agent = null;
        // 查询当前的fromUser是否已经绑定
        Agent user = AgentUserUtil.getAgentByUser(chatMessage.getFromUser());

        // msgType = event 才是微信的连接请求  user只有在用户断开连接之后才会为null

        if (!"event".equals(chatMessage.getMsgType()) && user == null && chatMessage.getMessageSource() == 2){
            System.out.println("进入评分系统");
            String statisticsId = AgentUserUtil.getStatisticsId(chatMessage.getFromUser());
            StatisReport statisReport = new StatisReport();
            statisReport.setStatisticsId(statisticsId);
            String content = chatMessage.getContent();
            if(content.equals("1")||content.equals("非常满意")){
                statisReport.setSatisfaction(1);
            }else if(content.equals("2")||content.equals("满意")){
                statisReport.setSatisfaction(2);
            }else if(content.equals("3")||content.equals("满意")){
                statisReport.setSatisfaction(3);
            }else if(content.equals("4")||content.equals("满意")){
                statisReport.setSatisfaction(4);
            }
            if (statisReport.getSatisfaction() != null){
                statisReportMapper.update(statisReport);
            }
            AgentUserUtil.deletetSatisfy(chatMessage.getFromUser());
            System.out.println("用户："+ chatMessage.getFromUser() + "，未进行评价");
            flowNumHandler.put(UUID.randomUUID().toString(),chatMessage);
            return;
        }

        // 用户离线操作
        if ("userBroken".equals(chatMessage.getMsgType())){
            if (AgentUserUtil.checkSatisfy(chatMessage.getFromUser()) && chatMessage.getMessageSource() == 2){
                ChatMessage message = new ChatMessage();
                message.setContent("请对本次服务作出评价，非常满意 请回数字1，满意 请回数字2，一般 请回数字3，不满意 请回数字4，感谢您的支持");
                message.setToUser(chatMessage.getFromUser());
                message.setFromUser(chatMessage.getToUser());
                message.setMessageSource(2);
                message.setMsgType("text");
                messageSendService.sendMessage(message);
            }

            // 通过离线用户获取对应的客服
            agent = AgentUserUtil.getAgentByUser(chatMessage.getFromUser());
            if (ListWaitUtil.checkUser(chatMessage.getFromUser())){
                ListWaitUtil.deleteUser("1",chatMessage.getFromUser());
            }
            if (AgentUserUtil.agentUser.size()>0){
                // 用户退出 结束聊天  把通话时长记录下来
                StatisReport statisReport = StatisReportUtil.cut(chatMessage.getFromUser());
                statisReportMapper.add(statisReport);

                AssignedUtil.disconnect(chatMessage.getFromUser());
                AgentUserUtil.deleteUser(chatMessage.getFromUser());
                // 如果当前断开的就是上面的
                ListWaitUtil.deleteUser("1",chatMessage.getFromUser());
                // 获取等待队列数组 对等待队列中的用户进行连接
                List<User> userList = ListWaitUtil.getUserList("1");
                if (userList.size() > 0){
                    User waitUser = userList.get(0);
                    AssignedUtil.link(agent);
                    AgentUserUtil.addUser(waitUser.getOpenId(),agent);
                    userList.remove(0);
                    chatMessage = waitUser.getMessage();

                    // 记录聊天时长
                    StatisReportUtil.addStatisReport(chatMessage.getFromUser(),"1",agent.getAgent(),1, chatMessage.getMessageSource());
                    // 增加满意度用户 用于挂断之后 发送消息进行满意度评价
                    if (chatMessage.getMessageSource() == 2){
                        StatisReport report = StatisReportUtil.getStatisReportByUserId(chatMessage.getFromUser());
                        AgentUserUtil.addSatisfy(chatMessage.getFromUser(),report.getStatisticsId());
                    }
                    // 移除等待队列之后 需要通知客服
                    sendListWaitToAgent();
                }
            }
        } else{
            // 如果已有客服绑定 就不再重写绑定
            if ( user == null && (agent = AssignedUtil.distribution(department)) != null) {
                AgentUserUtil.addUser(chatMessage.getFromUser(),agent);
                // 记录聊天时长
                StatisReportUtil.addStatisReport(chatMessage.getFromUser(),"1",agent.getAgent(),1, chatMessage.getMessageSource());
                // 增加满意度用户 用于挂断之后 发送消息进行满意度评价
                if (chatMessage.getMessageSource() == 2){
                    StatisReport report = StatisReportUtil.getStatisReportByUserId(chatMessage.getFromUser());
                    AgentUserUtil.addSatisfy(chatMessage.getFromUser(),report.getStatisticsId());
                }
            }
            if (user != null){
                agent = AssignedUtil.getAgentByAgentId(user.getAgent());
            }
            // 当可分配用户为 空时
            if (agent == null) {
                System.out.println("当前暂无可分配用户");
                if (!ListWaitUtil.checkUser(chatMessage.getFromUser())){
                    User user1 = new User();
                    String nickname = wxUserMapper.getNickname(chatMessage.getFromUser());
                    user1.setOpenId(chatMessage.getFromUser());
                    if (nickname != null){
                        user1.setNickname(nickname);
                    } else{
                        user1.setNickname(chatMessage.getFromUser());
                    }
                    user1.setMessage(chatMessage);
                    user1.setMessageSource(chatMessage.getMessageSource());
                    ListWaitUtil.add("1",user1);
                    // 发送等待队列给所有在线的客服
                    sendListWaitToAgent();
                }
                Integer listCount = ListWaitUtil.getCount("1",chatMessage.getFromUser());
                // 如果队伍接入已满 发送排队消息给用户
                ChatMessage message = new ChatMessage();
                message.setContent(listCount > 0?"您现在正在排队,前面还有" + listCount + "个用户" : "您现在正在排队,下一个就到您了");
                message.setToUser(chatMessage.getFromUser());
                message.setMsgType("event");
                message.setMessageSource(chatMessage.getMessageSource());
                messageSendService.sendMessage(message);
                return;
            }
            // 接受用户发送的消息 记录响应时长开始时间
            StatisReport statisReport = StatisReportUtil.getStatisReportByUserId(chatMessage.getFromUser());
            statisReport.setReceiveTime(new Date());
            statisReport.setIsRespond(1);
            statisReport.setIsLast(true);
        }


        // 微信在线用户
        if (chatMessage.getMessageSource() == 2 && !chatMessage.haveUser(chatMessage.getFromUser())){
            WxUser wxUser = wxUserMapper.getUserInfoByUsername(chatMessage.getFromUser());
            // 当前微信用户是否存在在数据库中
            if (wxUser != null){
                List<WxUser> userList = chatMessage.getUserList();
                wxUser.setMessageSource(2);
                userList.add(wxUser);
                //设置别名
                String alias = agentMapper.getAliasByUserId(chatMessage.getFromUser());
                wxUser.setAliasName(alias);
                chatMessage.setUserList(userList);
            }
        }
        // web在线用户
        List<String> userByAgent = AgentUserUtil.getUserByAgent(agent);
        for (String nickname:userByAgent){
            String alias = agentMapper.getAliasByUserId(nickname);
            chatMessage.setUserList2(nickname,null,nickname,alias,1);
        }

        System.out.println("当前客服已连接的用户：" + AgentUserUtil.agentUser.toString());
        System.out.println("用户：" + chatMessage.getFromUser() +"，已与客服："+ agent.getAgent() + "建立了连接");
        // 从微信过来的 toUser默认是公众号 所以需要变成客服
        if (chatMessage.getMessageSource() == 2){
            chatMessage.setToUser(agent.getAgent());
        }

        flowNumHandler.put(UUID.randomUUID().toString(),chatMessage);
        BridgeUtil.toClient(chatMessage,agent);
    }

}
